using DCOWebhook.Models;
using DCOWebhook.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Text;
using System.Text.RegularExpressions;

namespace DCOWebhook.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WebhookController : ControllerBase
    {
        private readonly ILogger<WebhookController> _logger;
        private readonly WebhookSettings _webhookSettings;
        private readonly SmtpSettings _smtpSettings;
        private readonly EmailSettings _emailSettings;
        private readonly IEmailService _emailService;

        public WebhookController(ILogger<WebhookController> logger, IOptions<WebhookSettings> webhookOptions, IOptions<SmtpSettings> smtpOptions, IOptions<EmailSettings> emailOptions, IEmailService emailService)
        {
            _logger = logger;
            _webhookSettings = webhookOptions.Value;
            _smtpSettings = smtpOptions.Value;
            _emailSettings = emailOptions.Value;
            _emailService = emailService;
        }

        [HttpPost]
        public async Task<IActionResult> ReceiveWebhook()
        {
            // 获取 Webhook 的签名（根据 Atomgit 的设置，假设使用 Secret Token）
            var signature = Request.Headers["X-AtomGit-Token"].FirstOrDefault();
            var events = Request.Headers["X-AtomGit-Event"].FirstOrDefault();

            // 验证签名
            // if (!string.IsNullOrEmpty(_webhookSettings.Secret) && signature != _webhookSettings.Secret)
            // {
            //     _logger.LogWarning("Webhook 签名验证失败。");
            //     return Unauthorized(new { message = "Unauthorized" });
            // }

            // 验证事件类型
            if (!events.Equals("push"))
            {
                _logger.LogWarning("Webhook 事件类型不支持。");
                return BadRequest(new { message = "Unsupported event type" });
            }

            // 读取请求体
            string requestBody;
            using (var reader = new StreamReader(Request.Body))
            {
                requestBody = await reader.ReadToEndAsync();
            }

            // 反序列化 JSON 负载
            WebhookPayload payload;
            try
            {
                payload = JsonConvert.DeserializeObject<WebhookPayload>(requestBody);
            }
            catch (JsonException ex)
            {
                _logger.LogError(ex, "解析 Webhook 负载失败。");
                return BadRequest(new { message = "Invalid payload" });
            }

            _logger.LogInformation($"处理仓库: {payload.Repository.Owner.Name}/{payload.Repository.Name}, Pusher: {payload.Commits.First().Author.Name}, Ref: {payload.Ref}");

            var invalidCommits = new List<Commit>();

            // DCO 正则表达式
            var dcoRegex = new Regex(@"^Signed-off-by:\s+([^<]+)<([^>]+)>$", RegexOptions.Multiline);

            foreach (var commit in payload.Commits)
            {
                _logger.LogDebug($"验证提交 {commit.Id} 的 DCO 签名。");

                // 检查 DCO 签名
                bool hasDco = dcoRegex.IsMatch(commit.Message);

                if (!hasDco)
                {
                    _logger.LogInformation($"提交 {commit.Id} 由 {commit.Author.Name} 创建，未通过 DCO 验证。");
                    invalidCommits.Add(commit);
                }
                else
                {
                    _logger.LogDebug($"提交 {commit.Id} 通过 DCO 验证。");
                }
            }

            if (invalidCommits.Any())
            {
                // 构建邮件内容
                var commitDetails = new StringBuilder();
                foreach (var commit in invalidCommits)
                {
                    commitDetails.AppendLine($"- **Commit SHA**: {commit.Id}");
                    commitDetails.AppendLine($"  - **作者**: {commit.Author.Name}");
                    commitDetails.AppendLine($"  - **消息**: {commit.Message}");
                    commitDetails.AppendLine($"  - **链接**: {commit.Url}\n");
                }

                var emailBody = _emailSettings.BodyTemplate.Replace("{Commits}", commitDetails.ToString());

                // 发送邮件通知
                try
                {
                    await _emailService.SendEmailAsync(_emailSettings.Subject, emailBody, _emailSettings.RecipientEmail);
                    _logger.LogInformation($"已发送邮件通知，包含 {invalidCommits.Count} 个未通过 DCO 验证的提交。");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "发送邮件通知失败。");
                }
            }
            else
            {
                _logger.LogInformation("所有提交均通过 DCO 验证。");
            }

            return Ok(new { message = "Processed" });
        }
    }
}
